<template>
  <div class="exam-records">
    <StudentNavbar title="考试记录" />
    
    <!-- 时间筛选条件 -->
    <el-card class="search-card">
      <template #header>
        <div class="card-header">
          <span>筛选条件</span>
        </div>
      </template>
      <el-form :model="searchForm" label-width="100px" inline>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="searchForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="searchForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchRecords" icon="el-icon-search">搜索</el-button>
          <el-button @click="resetSearch" icon="el-icon-refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 数据统计 -->
    <el-card class="stats-card">
      <template #header>
        <div class="card-header">
          <span>数据概览</span>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="stat-item">
            <div class="stat-icon bg-primary">
              <i class="el-icon-document"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ examRecords.length }}</div>
              <div class="stat-label">考试次数</div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-item">
            <div class="stat-icon bg-success">
              <i class="el-icon-medal"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ averageScore !== null ? averageScore.toFixed(1) : '0.0' }}</div>
              <div class="stat-label">平均分</div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-item">
            <div class="stat-icon bg-warning">
              <i class="el-icon-trophy"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ highestScore !== null ? highestScore : 0 }}</div>
              <div class="stat-label">最高分</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 考试记录列表 -->
    <el-card class="records-card">
      <template #header>
        <div class="card-header">
          <span>考试记录</span>
          <span class="record-count">共 {{ examRecords.length }} 条记录</span>
        </div>
      </template>
      
      <div v-if="examRecords.length === 0 && !loading" class="empty-state">
        <el-empty description="暂无考试记录"></el-empty>
      </div>
      
      <div v-else class="records-grid">
        <div 
          class="record-card" 
          v-for="record in examRecords" 
          :key="record.id"
        >
          <div class="record-header">
            <h3 class="subject-name">{{ record.subjectName }}</h3>
            <el-tag 
              :type="getScoreTagType(record)" 
              effect="dark"
            >
              {{ record.score }} / {{ record.totalScore }}
            </el-tag>
          </div>
          
          <div class="record-details">
            <div class="detail-item">
              <i class="el-icon-time"></i>
              <span>{{ formatDate(record.examTime) }}</span>
            </div>
            
            <div class="score-bar">
              <div class="score-progress">
                <div 
                  class="score-progress-fill" 
                  :style="{ 
                    width: (record.score / record.totalScore * 100) + '%',
                    backgroundColor: getScoreColor(record)
                  }"
                ></div>
              </div>
              <div class="score-percentage">
                {{ (record.score / record.totalScore * 100).toFixed(1) }}%
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 加载状态 -->
      <div class="loading-container" v-if="loading">
        <i class="el-icon-loading"></i>
        <span>加载中...</span>
      </div>
    </el-card>
  </div>
</template>

<script>
import StudentAPI from '@/api/student'
import StudentNavbar from '@/components/StudentNavbar.vue'

export default {
  name: 'ExamRecords',
  components: {
    StudentNavbar
  },
  data() {
    return {
      searchForm: {
        startTime: '',
        endTime: ''
      },
      examRecords: [],
      loading: false
    }
  },
  computed: {
    // 计算平均分
    averageScore() {
      if (this.examRecords.length === 0) return null
      const total = this.examRecords.reduce((sum, record) => sum + record.score, 0)
      return total / this.examRecords.length
    },
    
    // 计算最高分
    highestScore() {
      if (this.examRecords.length === 0) return null
      return Math.max(...this.examRecords.map(record => record.score))
    }
  },
  created() {
    this.fetchExamRecords()
  },
  methods: {
    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      const hours = String(d.getHours()).padStart(2, '0')
      const minutes = String(d.getMinutes()).padStart(2, '0')
      const seconds = String(d.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    
    // 获取分数标签类型
    getScoreTagType(record) {
      const percentage = record.score / record.totalScore
      if (percentage >= 0.8) return 'success'
      if (percentage >= 0.6) return 'warning'
      return 'danger'
    },
    
    // 获取分数颜色
    getScoreColor(record) {
      const percentage = record.score / record.totalScore
      if (percentage >= 0.8) return '#67c23a' // 绿色
      if (percentage >= 0.6) return '#e6a23c' // 橙色
      return '#f56c6c' // 红色
    },
    
    // 获取考试记录
    async fetchExamRecords() {
      this.loading = true
      try {
        const res = await StudentAPI.getScores()
        if (res.data.code === 200 && res.data.msg === 'success') {
          // 如果有搜索条件，则进行过滤
          let filteredRecords = res.data.data || []
          
          if (this.searchForm.startTime) {
            filteredRecords = filteredRecords.filter(record => 
              new Date(record.examTime) >= new Date(this.searchForm.startTime)
            )
          }
          
          if (this.searchForm.endTime) {
            filteredRecords = filteredRecords.filter(record => 
              new Date(record.examTime) <= new Date(this.searchForm.endTime)
            )
          }
          
          this.examRecords = filteredRecords
        } else {
          this.$message.error(res.data.message || '获取考试记录失败')
        }
      } catch (error) {
        console.error('获取考试记录失败:', error)
        this.$message.error('获取考试记录失败: ' + (error.response?.data?.message || error.message))
      } finally {
        this.loading = false
      }
    },

    // 搜索考试记录
    searchRecords() {
      this.fetchExamRecords()
    },

    // 重置搜索条件
    resetSearch() {
      this.searchForm.startTime = ''
      this.searchForm.endTime = ''
      this.fetchExamRecords()
    }
  }
}
</script>

<style scoped>
.exam-records {
  padding: 20px;
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  min-height: calc(100vh - 40px);
}

.search-card, .stats-card, .records-card {
  background: rgba(255, 255, 255, 0.08);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  margin-bottom: 30px;
  color: white;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 1.2rem;
  font-weight: 600;
}

.record-count {
  font-size: 0.9rem;
  opacity: 0.8;
}

.stat-item {
  display: flex;
  align-items: center;
  padding: 20px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  transition: all 0.3s ease;
}

.stat-item:hover {
  transform: translateY(-3px);
  background: rgba(255, 255, 255, 0.15);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 20px;
}

.bg-primary {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.bg-success {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.bg-warning {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.stat-number {
  font-size: 1.8rem;
  font-weight: 700;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 0.9rem;
  opacity: 0.8;
}

.records-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.record-card {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.05);
}

.record-card:hover {
  transform: translateY(-5px);
  background: rgba(255, 255, 255, 0.15);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.subject-name {
  margin: 0;
  font-size: 1.2rem;
  font-weight: 600;
}

.record-details {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.detail-item {
  display: flex;
  align-items: center;
  font-size: 0.9rem;
  opacity: 0.8;
}

.detail-item i {
  margin-right: 8px;
  font-size: 1.1rem;
}

.score-bar {
  display: flex;
  align-items: center;
  gap: 10px;
}

.score-progress {
  flex: 1;
  height: 8px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  overflow: hidden;
}

.score-progress-fill {
  height: 100%;
  border-radius: 4px;
  transition: width 0.5s ease;
}

.score-percentage {
  font-size: 0.9rem;
  font-weight: 600;
  min-width: 50px;
  text-align: right;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px;
  color: white;
  font-size: 1.2rem;
}

.loading-container i {
  font-size: 2rem;
  margin-right: 10px;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.empty-state {
  padding: 40px 0;
}

@media (max-width: 768px) {
  .records-grid {
    grid-template-columns: 1fr;
  }
  
  .stat-item {
    padding: 15px;
  }
  
  .stat-number {
    font-size: 1.5rem;
  }
  
  .record-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>